import {
	HOST
} from './confing.js'
import { getToken } from './storage.js'
import $Storage from '@/utils/storage.js'

const ajax = (option) => {
	const contentType = 'application/x-www-form-urlencoded';
	const token = getToken() || null;
	return new Promise((resolve, reject) => {
		uni.request({
			url: HOST + option.url,
			data: option.data || {},
			method: option.method,
			timeout: 1000 * 6,
			header: {
				"Content-Type": option.contentType ? option.contentType : contentType,
				'Token': token,
			},
			success: (res) => {
				console.log(res)
				if (res.data.code == 200) {
					resolve(res.data);
				} else if (res.data.code == 999) {
					uni.$u.toast('请先登录账号')
					$Storage.removeUserInfo();
					$Storage.removeToken();
					setTimeout(() => {
						uni.redirectTo({
							url: "/pages/login/login"
						})
					}, 1500)
					reject(res.data);
				} else {
					uni.$u.toast(res.data.msg || res.msg)
					reject(res.data);
				}
			},
			fail: err => {
				uni.$u.toast('请求失败')
				reject(err);
			},
		});
	})
}

/**
 * 上传文件
 */
const httpUploads = (files, relove, reject) => {
	const token = getToken() || null;
	uni.uploadFile({
		url: `${HOST}system/uploadAvatar`,
		filePath: files[0],
		header: {
			"enctype":"multipart/form-data",
			'Token': token,
		},
	})
		.then(result => {
			console.log(result)
			let data = JSON.parse(result[1].data);
			console.log('上传完毕', data);
			relove(data);
		})
		.catch(result => {
			reject(result);
			console.log('上传失败', result);
		});
}

export {
	ajax, httpUploads
}